package com.mall.seckill.listener;

import com.mall.constant.enums.OrderStatus;
import com.mall.constant.strings.ConstantStrings;
import com.mall.constant.strings.MapMsg;
import com.mall.entity.bargain.BgOrder;
import com.mall.seckill.entity.vo.SeckillItemVo;
import com.mall.seckill.service.SeckillOrderService;
import com.mall.utils.IdWorker;
import com.mall.utils.MatcherUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author White
 * @version 1.0
 * @email 616769721@qq.com
 * @date 2021/7/20 14:27
 */
@Component
public class IfOrderIdExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private Redisson redisson;

    @Autowired
    private SeckillOrderService seckillOrderService;


    public IfOrderIdExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message 信息
     * @param pattern 样式
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // message.toString()可以获取失效的key
        if (!MatcherUtil.match(ConstantStrings.IF_SECKILL_ORDER_ID_MATCH,message.toString())){
            System.out.println(message);
            return;
        }
        String[] keys = message.toString().split("ID:");
        System.out.println("orderID:"+keys[1]);
        BgOrder bgOrder = seckillOrderService.findOne(Long.parseLong(keys[1]));
        RMap<Object, Object> seckillItemMap = redisson.getMap(MapMsg.MALL_REDIS_MAP);
        RMap<Object, Integer> userMap = redisson.getMap(MapMsg.USER_REDIS_MAP+":"+bgOrder.getUid());
        //获取userMap的锁
        RLock userMapLock = userMap.getLock(bgOrder.getUid());
        //获取seckillItemMap的锁
        RLock seckillItemMapLock = seckillItemMap.getLock(bgOrder.getOrderItemId());
//        RLock lock = redisson.getLock(MapMsg.LOCK);
        try {
//            lock.lock(5, TimeUnit.SECONDS);
            seckillItemMapLock.lock(5, TimeUnit.SECONDS);
            userMapLock.lock(5, TimeUnit.SECONDS);
            Object seckillItemObject = seckillItemMap.get(bgOrder.getOrderItemId());
            if (seckillItemObject==null){
                System.out.println("gid:"+bgOrder.getUid()+"该商品秒杀活动已结束");
            }else {
                SeckillItemVo seckillItemVo=(SeckillItemVo)seckillItemObject;
                //回退，销量-1
                seckillItemVo.setSaleNum(seckillItemVo.getSaleNum()-1);
                //回退商品已出售百分比
                seckillItemVo.setRate((double)seckillItemVo.getSaleNum()/(double)seckillItemVo.getSeckillNum());
                seckillItemMap.put(bgOrder.getOrderItemId(),seckillItemVo);
                Integer userByCountObject = userMap.get(seckillItemVo.getGid());
                if (userByCountObject==null){
                    System.out.println("uid:"+bgOrder.getUid()+"该商品限购次数已重置");
                }else {
                    userMap.put(seckillItemVo.getGid(),userMap.get(seckillItemVo.getGid())-1);
                }
            }
        }finally {
//            lock.unlock();
            userMapLock.unlock();
            seckillItemMapLock.unlock();
        }
        seckillOrderService.updateOrderStatus(bgOrder.getId(), OrderStatus.BECAME_NVALID.getCode());
    }
}
